package com.chuji.crmcj.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.act.ClientDetailAct;
import com.chuji.crmcj.act.MainActivity;
import com.chuji.crmcj.bean.MagClientLoseDetailInfo;
import com.chuji.crmcj.bean.TaskRecordBySalesIDInfo;
import com.chuji.crmcj.bean.TaskRecordDetailsInfo;
import com.chuji.crmcj.utils.CommonUtil;
import com.chuji.crmcj.utils.Jump;
import com.chuji.crmcj.utils.NumberUtils;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by w.pitt on 2016/1/28.
 */
public class TaskFragment extends BaseFragment implements View.OnClickListener {
    /*待跟进客户*/
    private Button btn_follow_up_client;
    /*待跟进客户网络存储*/
    private List<TaskRecordBySalesIDInfo.ApiParamObjEntity> taskRecordData;
    /*待跟进客户数据*/
    private TaskRecordBySalesIDInfo taskRecordBySalesIDInfo;
    /*跟进记录*/
    private Button btn_follow_table;
    /*跟进记录网络存储*/
    private List<TaskRecordDetailsInfo.ApiParamObjEntity> taskRecordDetailsData;
    /*跟进记录数据*/
    private TaskRecordDetailsInfo taskRecordDetailsInfo;
    /*蓝色下划线*/
    private View follow_client_indicate_line;
    /*待跟进客户界面*/
    private LinearLayout ll_stand_follow_client;
    /*跟进记录界面*/
    private LinearLayout ll_follow_table;
    /*跟进记录内容*/
    private LinearLayout ll_table_content;
    /*待跟进客户*/
    private ListView lv_client_follow_up ;
    /*跟进记录*/
    private ExpandableListView lv_follow_table;
    /*屏幕宽度*/
    private int screenW;
    /*自定义适配器*/
    private CustomStandClientAdapter customStandClientAdapter;
    private CustomFollowTableAdapter customFollowTableAdapter;
    float y;
    String SalesID;
    @Override
    public void initData() {

    }
    @Override
    public void onResume() {
        super.onResume();
        customFollowTableAdapter.notifyDataSetChanged();
        for (int i = 0; i < customFollowTableAdapter.getGroupCount(); i++) {
            lv_follow_table.expandGroup(i);
        }
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mContext, R.layout.fragment_follow_client, null);
        //初始化组件
        btn_follow_up_client= (Button) view.findViewById(R.id.btn_follow_up_client);
        btn_follow_table= (Button) view.findViewById(R.id.btn_follow_table);
        follow_client_indicate_line=view.findViewById(R.id.follow_client_indicate_line);
        lv_client_follow_up= (ListView) view.findViewById(R.id.lv_client_follow_up);
        lv_follow_table= (ExpandableListView) view.findViewById(R.id.lv_follow_table);
        ll_stand_follow_client= (LinearLayout) view.findViewById(R.id.ll_stand_follow_client);
        ll_follow_table= (LinearLayout) view.findViewById(R.id.ll_follow_table);
        btn_follow_up_client .setTextColor(UIUtils.getColor(R.color.blue));
        ininDa();
        //销售员ID
        SalesID= SPUtils.getString(UIUtils.getContext(),"UserID","");
        //初始化适配器
        customStandClientAdapter=new CustomStandClientAdapter();
        customFollowTableAdapter=new CustomFollowTableAdapter();
        //数据

        //填充
        lv_client_follow_up.setAdapter(customStandClientAdapter);
        lv_follow_table.setAdapter(customFollowTableAdapter);
        //将所有项设置成默认展开
        int groupCount = lv_follow_table.getCount();

        for (int i=0;i<groupCount;i++) {

            lv_follow_table.expandGroup(i);

        };
        lv_follow_table.setGroupIndicator(null);


        screenW = ((MainActivity)mContext).getWindowManager().getDefaultDisplay().getWidth();
        lv_follow_table.setIndicatorBounds(screenW-100, screenW);
        follow_client_indicate_line.getLayoutParams().width = screenW / 2;
        return view;
    }
    public void ininDa(){
        //获取待跟进客户信息
        getStandFollowUpClient();
        //获取跟进记录信息
        getFollowUpNotes();
        //删除客户
//        deleteClient();
    }

    /**
     * 获取待跟进客户信息
     */
    private void getStandFollowUpClient() {
        if(taskRecordData==null){
            taskRecordData=new ArrayList<TaskRecordBySalesIDInfo.ApiParamObjEntity>();
        }
        //初始化Volley
        String strURL = String.format(UrlUtils.GET_TASK_RECORD_BY_SALESID+"&SalesID="+SalesID+"&PageSize="+"20"+"&&PageIndex="+"1");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                taskRecordBySalesIDInfo = JSON.parseObject(response, TaskRecordBySalesIDInfo.class);
                taskRecordData.addAll(taskRecordBySalesIDInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断adapter是否创建
                        if (customStandClientAdapter == null) {
                            //创建适配器
                            customStandClientAdapter=new CustomStandClientAdapter();
                            //填充数据
                            lv_client_follow_up.setAdapter(customStandClientAdapter);
                        } else {
                            customStandClientAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    /**
     * 获取跟进记录信息
     */
    private void getFollowUpNotes() {
        if(taskRecordDetailsData==null){
            taskRecordDetailsData=new ArrayList<TaskRecordDetailsInfo.ApiParamObjEntity>();
        }
        //初始化Volley
        String strURL = String.format(UrlUtils.GET_TASK_RECORD_DETAILS_FOR_SALESID+"&SalesID="+SalesID+"&PageSize="+"20"+"&&PageIndex="+"1");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                taskRecordDetailsInfo = JSON.parseObject(response, TaskRecordDetailsInfo.class);
                taskRecordDetailsData.addAll(taskRecordDetailsInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断adapter是否创建
                        if (customFollowTableAdapter == null) {
                            //创建适配器
                            customFollowTableAdapter=new CustomFollowTableAdapter();
                            //填充数据
                            lv_follow_table.setAdapter(customFollowTableAdapter);
//                            //将所有项设置成默认展开
//                            int groupCount = lv_follow_table.getCount();
//
//                            for (int i=0; i<groupCount; i++) {
//
//                                lv_follow_table.expandGroup(i);
//
//                            };
//                            lv_follow_table.setGroupIndicator(null);
                        } else {
                            customFollowTableAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }



    private void showRemoveClientDialog(final int i, final String TaskRecordID) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(mContext, R.layout.dialog_remove_client, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        final TextView mTvFolType = (TextView) view.findViewById(R.id.tv_isfollow);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String strURL = String.format(UrlUtils.DELETE_tASK_RECORD+"&TaskRecordID="+TaskRecordID);
                StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        UIUtils.runInMainThread(new Runnable() {
                            @Override
                            public void run() {
                                taskRecordData.remove(i);
                                customFollowTableAdapter.notifyDataSetChanged();
                                UIUtils.showToastSafe("删除成功");
                            }
                        });
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        System.out.println("失败" + error);
                        UIUtils.showToastSafe("请检查网络");
                    }
                });
                // Add the request to the RequestQueue.
                VolleyUtil.getRequestQueue().add(stringRequest);
                dialog.dismiss();
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    @Override
    public void initListener() {
        btn_follow_up_client.setOnClickListener(this);
        btn_follow_table.setOnClickListener(this);
    }
    public void lineTranslation(int startX, int finishX) {
        y= follow_client_indicate_line.getY();
        TranslateAnimation ta = new TranslateAnimation(startX, finishX, 0, 0);
        ta.setDuration(200);
        ta.setFillAfter(true);
        follow_client_indicate_line.setAnimation(ta);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_follow_up_client:
                follow_client_indicate_line.requestLayout(); // 重新计算大小，并刷新控件
                lineTranslation(screenW / 2, 0);
                btn_follow_table.setTextColor(UIUtils.getColor(R.color.btn_color));
                btn_follow_up_client .setTextColor(UIUtils.getColor(R.color.blue));
                ll_stand_follow_client.setVisibility(View.VISIBLE);
                ll_follow_table.setVisibility(View.GONE);
                break;
            case R.id.btn_follow_table:
                follow_client_indicate_line.requestLayout(); // 重新计算大小，并刷新控件
                lineTranslation(0, screenW / 2);
                btn_follow_up_client.setTextColor(UIUtils.getColor(R.color.btn_color));
                btn_follow_table.setTextColor(UIUtils.getColor(R.color.blue));
                ll_stand_follow_client.setVisibility(View.GONE);
                ll_follow_table.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    /**
     * 自定义适配器
     */
    class CustomStandClientAdapter extends BaseAdapter {
        private Context context;
        Intent intent;
        @Override
        public int getCount() {
            return taskRecordData.size();
        }

        @Override
        public Object getItem(int i) {
            return taskRecordData.get(i);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            StandViewHolder standViewHolder=null;
            if(view==null) {
                standViewHolder = new StandViewHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.listview_client_follow_up, null);
                standViewHolder.mTv_client_name = (TextView) view.findViewById(R.id.tv_client_name);
                standViewHolder.mIv_important_client = (ImageView) view.findViewById(R.id.iv_important_client);
                standViewHolder.mIv_manager_appiont = (ImageView) view.findViewById(R.id.iv_manager_appiont);
                standViewHolder.mIv_follow_client = (ImageView) view.findViewById(R.id.iv_follow_client);
                standViewHolder.mIv_order_client = (ImageView) view.findViewById(R.id.iv_order_client);
                standViewHolder.mTv_client_phoneNumber = (TextView) view.findViewById(R.id.tv_client_phoneNumber);
                standViewHolder.mTv_car_type = (TextView) view.findViewById(R.id.tv_car_type);
                standViewHolder.mTv_intent_car_type = (TextView) view.findViewById(R.id.tv_intent_car_type);
                view.setTag(standViewHolder);
            }else{
                standViewHolder = (StandViewHolder) view.getTag();
            }
            if(taskRecordData.size()!=0) {
                standViewHolder.mTv_client_name.setText(taskRecordData.get(position).getName());
                standViewHolder.mTv_client_phoneNumber.setText(taskRecordData.get(position).getTel());
                standViewHolder.mTv_car_type.setText(taskRecordData.get(position).getCarModel());
                //判断是否是重点客户
                if(taskRecordData.get(position).isIsImportance()==true){
                    standViewHolder.mIv_important_client.setVisibility(View.VISIBLE);
                }else {
                    standViewHolder.mIv_important_client.setVisibility(View.GONE);
                }
                //判断是否是订单客户
                if(taskRecordData.get(position).getIsOrderCustomer()=="0"){
                    standViewHolder.mIv_order_client.setVisibility(View.VISIBLE);
                    standViewHolder.mTv_intent_car_type.setText("订单车型");
                }else {
                    standViewHolder.mIv_order_client.setVisibility(View.GONE);
                }
                //判断是否是系统跟进客户
                if(taskRecordData.get(position).isIsSystem()==true){
                    standViewHolder.mIv_follow_client.setVisibility(View.VISIBLE);
                }else {
                    standViewHolder.mIv_follow_client.setVisibility(View.GONE);
                }
                //判断是否是经理指派的
                if(taskRecordData.get(position).isIsAssign()==true){
                    standViewHolder.mIv_manager_appiont.setVisibility(View.VISIBLE);
                }else {
                    standViewHolder.mIv_manager_appiont.setVisibility(View.GONE);
                }
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        //给ListView设置点击事件
                        lv_client_follow_up.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                //传递客户ID
                                intent = new Intent(UIUtils.getContext(),ClientDetailAct.class);
                                intent.putExtra("CustomerID", taskRecordDetailsData.get(position).getCustomerID());
                                startActivity(intent);
                            }
                        });
                        //给ListView设置长按事件
                        lv_client_follow_up.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                            @Override
                            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                                /**
                                 *  弹出消息框
                                 */
                                if(taskRecordData.get(0).isIsSystem()==true){
                                    UIUtils.showToastSafe("不可删除");
                                }else {
                                    showRemoveClientDialog(i,taskRecordBySalesIDInfo.getApiParamObj().get(0).getTaskRecordID());
                                }
                                return true;
                            }
                        });
                    }
                });
            }else{
                UIUtils.showToastSafe("暂无数据");
            }
            return view;
        }
        class StandViewHolder{
            private TextView mTv_client_name;
            private ImageView mIv_important_client;
            private ImageView mIv_manager_appiont;
            private ImageView mIv_follow_client;
            private ImageView mIv_order_client;
            private TextView mTv_client_phoneNumber;
            private TextView mTv_car_type;
            private TextView mTv_intent_car_type;

        }
    }
    /**
     * 跟进记录适配器
     */
    class CustomFollowTableAdapter extends BaseExpandableListAdapter {
        private TextView mTv_follow_time;
        private LinearLayout mLl_table_content;
        private TextView mTv_client_name;
        private TextView mTv_client_phoneNumber;
        private TextView mTv_follow_title;
        private TextView mTv_communicate_time;
        private TextView mTv_follow_type;
        private TextView mTv_try_information;
        Intent intent;
        @Override
        public int getGroupCount() {
            return taskRecordDetailsData.size();
        }

        @Override
        public int getChildrenCount(int i) {
            return Integer.parseInt(taskRecordDetailsData.get(i).getNum());
        }

        @Override
        public Object getGroup(int i) {
            return taskRecordDetailsData.get(i);
        }

        @Override
        public Object getChild(int i, int i1) {
            return taskRecordDetailsData.get(i);
        }

        @Override
        public long getGroupId(int i) {
            return i;
        }

        @Override
        public long getChildId(int i, int i1) {
            return i1;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
//            GroupviewHolder groupviewHolder=null;
            if(view==null) {
//                groupviewHolder = new GroupviewHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.listview_follow_up_table, null);
                mTv_follow_time = (TextView) view.findViewById(R.id.tv_follow_time);
//                view.setTag(groupviewHolder);
            }else{
//                groupviewHolder = (GroupviewHolder) view.getTag();
            }
            view.setClickable(true);
            if(taskRecordDetailsData.size()!=0){
                mTv_follow_time.setText(taskRecordDetailsData.get(0).getCreateTime());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        lv_follow_table.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                            @Override
                            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
                                //传递客户ID
                                intent = new Intent(UIUtils.getContext(),ClientDetailAct.class);
                                intent.putExtra("CustomerID", taskRecordDetailsData.get(0).getCustomerID());
                                startActivity(intent);
                                return false;
                            }
                        });
                    }
                });
            }else{
                UIUtils.showToastSafe("暂无数据");
            }
            return view;
        }
        @Override
        public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
//            ChildviewHolder childviewHolder=null;
            if(view==null) {
//                childviewHolder = new ChildviewHolder();
                view = LayoutInflater.from(mContext).inflate(R.layout.listview_follow_oneday_table, null);
                mLl_table_content = (LinearLayout) view.findViewById(R.id.ll_table_content);
                mTv_client_name = (TextView) view.findViewById(R.id.tv_client_name);
                mTv_client_phoneNumber = (TextView) view.findViewById(R.id.tv_client_phoneNumber);
                mTv_follow_title = (TextView) view.findViewById(R.id.tv_follow_title);
                mTv_communicate_time = (TextView) view.findViewById(R.id.tv_communicate_time);
                mTv_follow_type = (TextView) view.findViewById(R.id.tv_follow_type);
                mTv_try_information = (TextView) view.findViewById(R.id.tv_try_information);
//                childviewHolder.mLl_table_content = (LinearLayout) view.findViewById(R.id.ll_table_content);
//                childviewHolder.mTv_client_name = (TextView) view.findViewById(R.id.tv_client_name);
//                childviewHolder.mTv_client_phoneNumber = (TextView) view.findViewById(R.id.tv_client_phoneNumber);
//                childviewHolder.mTv_follow_title = (TextView) view.findViewById(R.id.tv_follow_title);
//                childviewHolder.mTv_communicate_time = (TextView) view.findViewById(R.id.tv_communicate_time);
//                childviewHolder.mTv_follow_type = (TextView) view.findViewById(R.id.tv_follow_type);
//                childviewHolder.mTv_try_information = (TextView) view.findViewById(R.id.tv_try_information);
//                view.setTag(childviewHolder);
            }else{
//                childviewHolder = (ChildviewHolder) view.getTag();
            }
            if(taskRecordDetailsData.size()!=0){
                mTv_client_name.setText(taskRecordDetailsData.get(i1).getName());
                if(taskRecordDetailsData.get(0).getTel().length()==11) {
                    mTv_client_phoneNumber.setText(NumberUtils.parsePhoneNumber(taskRecordDetailsData.get(0).getTel()));
                }else{
                    mTv_client_phoneNumber.setText(taskRecordDetailsData.get(0).getTel());
                }
                mTv_follow_title.setText(taskRecordDetailsData.get(i1).getTaskTypeContent());
                mTv_communicate_time.setText(taskRecordDetailsData.get(i1).getCreateTime());
                //判断很客户沟通的途径
                if(taskRecordDetailsData.get(i1).getTaskType()=="0"){
                    mTv_follow_type.setText("客户来店");
                }else if(taskRecordDetailsData.get(i1).getTaskType()=="1"){
                    mTv_follow_type.setText("电话");
                }else if(taskRecordDetailsData.get(i1).getTaskType()=="2"){
                    mTv_follow_type.setText("短信");
                }else if(taskRecordDetailsData.get(i1).getTaskType()=="3"){
                    mTv_follow_type.setText("其他");
                }else{

                }
                //跟客户沟通的内容
                mTv_try_information.setText(taskRecordDetailsData.get(i1).getTaskDetail());
//                childviewHolder.mTv_client_name.setText(taskRecordDetailsData.get(i1).getName());
////                childviewHolder.mTv_client_phoneNumber.setText(NumberUtils.parsePhoneNumber(taskRecordDetailsData.get(0).getTel()));
//                childviewHolder.mTv_client_phoneNumber.setText("123-128-123456");
//                childviewHolder.mTv_follow_title.setText(taskRecordDetailsData.get(i1).getTaskTypeContent());
//                childviewHolder.mTv_communicate_time.setText(taskRecordDetailsData.get(i1).getCreateTime());
//                //判断很客户沟通的途径
//                if(taskRecordDetailsData.get(i1).getTaskType()=="0"){
//                    childviewHolder.mTv_follow_type.setText("客户来店");
//                }else if(taskRecordDetailsData.get(i1).getTaskType()=="1"){
//                    childviewHolder.mTv_follow_type.setText("电话");
//                }else if(taskRecordDetailsData.get(i1).getTaskType()=="2"){
//                    childviewHolder.mTv_follow_type.setText("短信");
//                }else if(taskRecordDetailsData.get(i1).getTaskType()=="3"){
//                    childviewHolder.mTv_follow_type.setText("其他");
//                }else{
//
//                }
//                //跟客户沟通的内容
//                childviewHolder.mTv_try_information.setText(taskRecordDetailsData.get(i1).getTaskDetail());
            }else{
                UIUtils.showToastSafe("暂无数据");
            }
            return view;

        }
//        class GroupviewHolder{
//            private TextView mTv_follow_time;
//        }
//        class ChildviewHolder{
//            private LinearLayout mLl_table_content;
//            private TextView mTv_client_name;
//            private TextView mTv_client_phoneNumber;
//            private TextView mTv_follow_title;
//            private TextView mTv_communicate_time;
//            private TextView mTv_follow_type;
//            private TextView mTv_try_information;
//        }
        @Override
        public boolean isChildSelectable(int i, int i1) {
            return true;
        }
    }
}
